package wsz.file.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wsz.file.util.SpeedLimit;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author wsz
 * @date 2022/4/6 14:55
 **/
@RestController
@RequestMapping("file")
public class FileController {

    /**
     * 正常下载
     * @param response
     */
    @GetMapping("/common")
    public void common(HttpServletResponse response) {

        try {
            // 下载本地文件
            String fileName = "Dubbo讲义.pdf";
            // 读到流中
            InputStream inStream = new FileInputStream("c:/Dubbo讲义.pdf");
            // 设置输出的格式
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename=" +
                    new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            response.getOutputStream().flush();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 限制下载速度
     * @param response
     */
    @GetMapping("/limit")
    public void limiter(HttpServletResponse response) {

        try {
            // 下载本地文件
            String fileName = "Dubbo讲义.pdf";
            // 读到流中
            InputStream inStream = new FileInputStream("c:/Dubbo讲义.pdf");
            // 设置输出的格式
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename=" +
                    new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            // 循环取出流中的数据

            byte[] buffer = new byte[1024];
            int read = 0;
            // 限制速度kb
            SpeedLimit limit = new SpeedLimit(100);
            do {
                if (limit != null) {
                    limit.doLimit(buffer.length);
                }
                read = inStream.read(buffer, 0, buffer.length);
                response.getOutputStream().write(buffer, 0, read);
            } while (read == buffer.length);

            response.getOutputStream().flush();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
